package com.audio;

import javax.sound.sampled.*;
import java.io.*;

/**
 * javasound
 */
public class AudioSplitter {

    /**
     * 分割音频文件
     *
     * @param inputFile            输入音频文件路径
     * @param outputDir            输出文件夹路径
     * @param splitDurationSeconds 每段音频的时长（秒）
     * @throws Exception 可能抛出IO或音频处理异常
     */
    public static void splitAudio(File inputFile, String outputDir, int splitDurationSeconds) throws Exception {
        // 加载音频文件
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(inputFile);
        AudioFormat audioFormat = audioInputStream.getFormat();
        long totalFrames = audioInputStream.getFrameLength();
        float frameRate = audioFormat.getFrameRate();
        long totalDurationSeconds = (long) (totalFrames / frameRate);

        System.out.println("音频总时长: " + totalDurationSeconds + " 秒");

        // 计算每段分割的帧数
        long framesPerSplit = (long) (frameRate * splitDurationSeconds);
        int frameSize = audioFormat.getFrameSize();
        byte[] buffer = new byte[(int) (framesPerSplit * frameSize)];

        int partNumber = 1;
        long framesRead = 0;

        // 循环读取和写入分割片段
        while (framesRead < totalFrames) {
            // 读取当前分割片段的字节数据
            long bytesToRead = Math.min(buffer.length, (totalFrames - framesRead) * frameSize);
            int bytesRead = audioInputStream.read(buffer, 0, (int) bytesToRead);

            if (bytesRead <= 0) {
                break;
            }

            // 保存分割片段
            File outputFile = new File(outputDir, "split_part_" + partNumber + ".wav");
            try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, bytesRead);
                 AudioInputStream segmentStream = new AudioInputStream(bais, audioFormat, bytesRead / frameSize)) {
                AudioSystem.write(segmentStream, AudioFileFormat.Type.WAVE, outputFile);
            }

            System.out.println("保存分割片段: " + outputFile.getAbsolutePath());
            partNumber++;
            framesRead += bytesRead / frameSize;
        }

        // 关闭流
        audioInputStream.close();
        System.out.println("音频分割完成!");
    }

    public static void main(String[] args) {
        try {
            // 输入音频文件路径
            File inputFile = new File("D:\\Code idea\\AudioDemo\\src\\main\\resources\\static\\in\\test.wav");
            // 输出文件夹路径
            String outputDir = "D:\\Code idea\\AudioDemo\\src\\main\\resources\\static\\out";
            // 每段音频的时长（秒）
            int splitDurationSeconds = 10;

            // 创建输出目录（如果不存在）
            File outputDirectory = new File(outputDir);
            if (!outputDirectory.exists()) {
                outputDirectory.mkdirs();
            }

            // 分割音频
            splitAudio(inputFile, outputDir, splitDurationSeconds);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("音频分割失败: " + e.getMessage());
        }
    }
}
